﻿using FI.Core.Configuration;
using FI.Core.IoC;
using FI.Core.Utilities;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FI.Core.Caching.Configuration
{
    /// <summary>
    /// Define FI.caching based configuration section.
    /// </summary>
    [ConfigurationSectionName(Constants.ConfigurationSections.Caching)]
    public class CachingSettings : ServiceLocatableSettings
    {
        private const string CacheStoreFactoriesProperty        = "cacheStoreFactories";
        private const string DefaultCacheStoreFactoryProperty   = "defaultCacheStoreFactory";

        /// <summary>
        /// Sets or gets the name of default cache store factory.
        /// </summary>
        [ConfigurationProperty(DefaultCacheStoreFactoryProperty,IsRequired = false)]
        public string DefaultCacheStoreFactory
        {
            get { return (string)base[DefaultCacheStoreFactoryProperty]; }
            set { base[DefaultCacheStoreFactoryProperty] = value; }
        }
            
        /// <summary>
        /// Gets or sets cache store factories.
        /// </summary>
        [ConfigurationProperty(CacheStoreFactoriesProperty, IsRequired = false)]
        public NameTypeConfigurationElementCollection<CacheStoreFactoryDataBase> CacheStoreFactories
        {
            get { return (NameTypeConfigurationElementCollection<CacheStoreFactoryDataBase>)base[CacheStoreFactoriesProperty]; }
            set { base[CacheStoreFactoriesProperty] = value; }
        }

        #region Public Methods
        /// <summary>
        /// Configures the specified service locator.
        /// </summary>
        /// <param name="serviceLocator">The service locator.</param>
        public override void Configure(IServiceLocator serviceLocator)
        {
            Guard.ArgumentNotNull(serviceLocator, "serviceLocator");
            foreach (CacheStoreFactoryDataBase cacheStoreFactoryData in this.CacheStoreFactories)
            {
                var creator = cacheStoreFactoryData.GetProviderCreator(this);
                if (null != creator)
                {
                    serviceLocator.Register<ICacheStoreFactory>(creator, cacheStoreFactoryData.Name, cacheStoreFactoryData.Name == this.DefaultCacheStoreFactory, cacheStoreFactoryData.Lifetime);
                }
            }
        }
        #endregion
    }
}
